﻿using System;
using System.Linq;
using System.Collections.Generic;

using Microsoft.WindowsMobile.Status;
using Microsoft.WindowsMobile.PocketOutlook;

namespace iPhoneUI.Widgets
{
    /// <summary>
    /// A helper class to help sort out the four exposed SystemState calendar events
    /// </summary>
    class AppointmentHelper
    {
        private IEnumerable<Appointment> m_appointments = new List<Appointment>();

        public AppointmentHelper()
        {
        }

        /// <summary>
        /// The organized collection of events
        /// </summary>
        public IEnumerable<Appointment> Appointments
        {
            get
            {
                return m_appointments;
            }
        }

        /// <summary>
        /// For recurring appointments on the home screen the Appointment object has the recurrance data
        /// not the data for the next occurence. This method attempts to dereference to the next occurance
        /// </summary>
        /// <param name="appointment"></param>
        /// <returns>appointment or the next occurance of appointment from today or tomorrow</returns>
        private Appointment ResolveAppointment(Appointment appointment)
        {
            // if it is a recurring appointment try to find and instance for today or tomorrow
            if (appointment != null && appointment.IsRecurring)
            {
                // first see if there is an occurance today that has not already ended
                Appointment a = appointment.RecurrencePattern.GetOccurrence(DateTime.Now);
                if (a != null && a.End > DateTime.Now)
                    return a;

                // no occurence today - let's try tomorrow
                return appointment.RecurrencePattern.GetOccurrence(DateTime.Now.AddDays(1));
            }

            return appointment;
        }

        /// <summary>
        /// Refreshes the contents of the Appontments collection
        /// </summary>
        public void Refresh()
        {
            List<Appointment> list = new List<Appointment>();
            list.Add(ResolveAppointment(SystemState.CalendarHomeScreenAppointment));
            list.Add(ResolveAppointment(SystemState.CalendarAppointment));
            list.Add(ResolveAppointment(SystemState.CalendarNextAppointment));
            list.Add(ResolveAppointment(SystemState.CalendarEvent));

            // filter out items that might be associated with two or more SystemStates
            // (for instance is both home screen appointment and next appointment) or that
            // may have already ended - and then order by the start time of the remainder
            m_appointments = list.Where(a => a != null && a.End > DateTime.Now).Distinct(new AppointmentEqualityComparer()).OrderBy(a => a.Start);
        }
    }
}
